package com.hc.summary.room.database;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.hc.summary.room.dao.WordDao;
import com.hc.summary.room.entity.Word;

@Database(entities = {Word.class},version = 1,exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
    private static WordDatabase instance;

    public static WordDatabase getInstance(Context context){
        if(instance == null){
            instance = Room.databaseBuilder(context.getApplicationContext(),WordDatabase.class,"WordDatabase")
                    .addMigrations(migration_1_2,migration_2_3)
                    .build();
        }
        return instance;
    }
    public abstract WordDao getWordDao();

    static Migration migration_1_2 = new Migration(1,2) { //增加字段
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE word ADD COLUMN Test TEXT");
        }
    };
    static Migration migration_2_3 = new Migration(2,3) { //删除字段
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE word_temp (id INTEGER PRIMARY KEY NOT NULL,English TEXT,Chinese TEXT)");
            database.execSQL("INSERT INTO word_temp(id,English,Chinese) SELECT id,English,Chinese FROM word");
            database.execSQL("DROP TABLE word");
            database.execSQL("ALTER TABLE word_temp RENAME TO word");
        }
    };
}
